package com.baidu.bas.magic.ext.mudule;

import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.config.MagicModule;
import org.ssssssss.magicapi.context.RequestContext;
import org.ssssssss.script.annotation.Comment;

import javax.servlet.http.HttpServletRequest;

import static com.baidu.bas.annotation.constant.ReqAttrKey.TENANCY;

/**
 * 扩展request 模块
 * @author liuzhenchuan@foxmail.com
 * @date 2021/3/11
 */
@Component
public class XRequestModule implements MagicModule {

    @Comment("获取请求中的属性")
    public String getAttr(@Comment("参数名") String name) {
        HttpServletRequest request = this.get();
        if (request != null) {
            return (String) request.getAttribute(name);
        } else {
            return null;
        }
    }

    @Comment("获取当前租户")
    public String getTenancy(String defaultValue) {
        String tenancy = getAttr(TENANCY);
        if(tenancy==null){
            return defaultValue;
        }
        return tenancy;
    }

    public HttpServletRequest get() {
        return RequestContext.getHttpServletRequest();
    }

    @Override
    public String getModuleName() {
        return "requestx";
    }
}
